package com.server.transaction.aspect;

import cn.hutool.core.date.DateUtil;
import com.server.framework.utils.JsonUtils;
import com.server.transaction.annotation.SecureInvoke;
import com.server.transaction.domain.dto.SecureInvokeDTO;
import com.server.transaction.domain.entity.SysSecureRecord;
import com.server.transaction.service.CheckHandle;
import com.server.transaction.service.SecureInvokeHandle;
import com.server.transaction.service.SecureInvokeHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @title: SecureInvokeAspect
 * @author: gyuan
 * @description
 * @date: 2023-11-16 18:02
 */
@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 1) //确保最先执行
public class SecureInvokeAspect {

    @Autowired
    private SecureInvokeHandle secureInvokeHandle;

    @Around(value = "@annotation(secureInvoke)")
    public Object around(ProceedingJoinPoint joinPoint, SecureInvoke secureInvoke) throws Throwable {
        if(!TransactionSynchronizationManager.isActualTransactionActive() || SecureInvokeHolder.isInvoking()) {
            return joinPoint.proceed();
        }
        log.info("start execute local message transaction");
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String methodName = method.getName();
        List<String> parameterTypeList = Stream.of(method.getParameterTypes()).map(Class::getName).collect(Collectors.toList());
        // 创建回调对象
        Class<? extends CheckHandle> rollback = secureInvoke.rollback();

        SecureInvokeDTO secureInvokeDTO = SecureInvokeDTO.builder()
                .className(method.getDeclaringClass().getName())
                .methodName(methodName)
                .parameterTypes(JsonUtils.toJsonString(parameterTypeList))
                .args(JsonUtils.toJsonString(joinPoint.getArgs()))
                .build();

        SysSecureRecord invokeRecord = SysSecureRecord.builder()
                .secureInvokeDTO(secureInvokeDTO)
                .maxRetryTimes(secureInvoke.maxRetryTimes())
                .nextRetryTime(DateUtil.offsetMinute(new Date(), SecureInvokeHandle.RETRY_INTERVAL_MINUTES))
                .rollbackClass(rollback.getName())
                .build();
        return secureInvokeHandle.invoke(invokeRecord,secureInvoke.async());
    }

}
